﻿using System;
using DataService.Enums;
using DataService.Group;
using DataService.Structs;

namespace DataService.Tag;

public sealed class ShortTag : TagBase
{

    public ShortTag(short id, DeviceAddress addr, IGroup group)
        : base(id, addr, group)
    {
    }


    #region IDevice Members
    public override bool Refresh(DataSource source = DataSource.Device)
    {
        var _newvalue = _group.ReadInt16(_plcAddress, source);
        if (_newvalue.Value != _value.Int16)
        {
            Storage value = Storage.Empty;
            value.Int16 = _newvalue.Value;
            DateTime time = _newvalue.TimeStamp.ToDateTime();
            if (ValueChanging != null)
            {
                ValueChanging(this, new ValueChangingEventArgs<Storage>(_newvalue.Quality, _value, value, _timestamp, time));
            }
            _timestamp = time;
            _quality = _newvalue.Quality;
            if (_quality == QUALITIES.QUALITY_GOOD)
            {
                _value = value;
                if (ValueChanged != null)
                {
                    ValueChanged(this, new ValueChangedEventArgs(value));
                }
            }
            return true;
        }
        return false;
    }

    public override Storage Read(DataSource source = DataSource.Cache)
    {
        Storage value = Storage.Empty;
        value.Int16 = _group.ReadInt16(_plcAddress, source).Value;
        return value;
    }

    public override int Write(object value)
    {
        var temp = _value.Int16;
        var str = value as string;
        if (str == null)
            temp = Convert.ToInt16(value);
        else if (!short.TryParse(str, out temp))
            return -1;
        //_timeStamp = DateTime.Now;
        return _group.WriteInt16(_plcAddress, temp);
    }

    protected override int InnerWrite(Storage value)
    {
        return _group.WriteInt16(_plcAddress, value.Int16);
    }

    #endregion

    public override string ToString()
    {
        return _value.Int16.ToString();
    }
}
